package com.hhhn.wk.main;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.main.fragment.BlankFragment01;
import com.hhhn.wk.main.fragment.TabFragment01;
import com.hhhn.wk.main.fragment.TabFragment02;
import com.hhhn.wk.main.fragment.TabFragment03;
import com.hhhn.wk.main.fragment.TabFragment04;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.Jsondes;
import com.hhhn.wk.utils.StatusBarUtil;
import com.hhhn.wk.widget.versionsup.up.ApkUtils;
import com.hhhn.wk.widget.versionsup.up.SDCardUtils;
import com.hhhn.wk.widget.versionsup.updataservice.UpdataService;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
 * * * * * * * * * * * *
 *
 * @author：WenKe ｡◕‿◕｡ *
 * Data：2017     ｡◕‿◕｡ *
 * QQ：370820580  ｡◕‿◕｡ *
 * Function：     ｡◕‿◕｡ *
 * <p>
 * * * * * * * * * * *
 */
public class MainActivity extends BaseActivity {
    private static String APPNAMEname = "hhhn.apk";//app名字
    private PackageInfo packInfo;
    private String versionname;
    private int versioncode;
    //再按一次退出程序
    private boolean mBackKeyPressed = false;
    private Context context;
    private BaseActivity activity;
    //fragment管理类
    private FragmentManager mFragmentManager;
    private FragmentTransaction mFragmentTransaction;
    private TextView tv_tab01;
    private TextView tv_tab02;
    private TextView tv_tab03;
    private TextView tv_tab04;
    private ImageView iv_bar1;
    private ImageView iv_bar2;
    private ImageView iv_bar3;
    private ImageView iv_bar4;
//    private BlankFragment01 f1;
    private TabFragment01 f1;
    private TabFragment02 f2;
    private TabFragment03 f3;
    private TabFragment04 f4;
//    //声明AMapLocationClient类对象
//    public AMapLocationClient mLocationClient = null;
//    //声明定位回调监听器
//    public AMapLocationListener mLocationListener = null;
//
//    //声明AMapLocationClientOption对象
//    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_main);
        StatusBarUtil.setTransparentForImageViewInFragment(MainActivity.this, null);
        context = MainActivity.this;
        activity = this;
    }

    @Override
    protected void initView() {
        iv_bar1 = (ImageView) findViewById(R.id.iv_bar1);
        iv_bar2 = (ImageView) findViewById(R.id.iv_bar2);
        iv_bar3 = (ImageView) findViewById(R.id.iv_bar3);
        iv_bar4 = (ImageView) findViewById(R.id.iv_bar4);
        tv_tab01 = (TextView) findViewById(R.id.tv_tab01);
        tv_tab02 = (TextView) findViewById(R.id.tv_tab02);
        tv_tab03 = (TextView) findViewById(R.id.tv_tab03);
        tv_tab04 = (TextView) findViewById(R.id.tv_tab04);
        f1 = new TabFragment01();
        f2 = new TabFragment02();
        f3 = new TabFragment03();
        f4 = new TabFragment04();
        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();

        mFragmentTransaction.add(R.id.mainFrameLayout, f1, "f1");
        mFragmentTransaction.add(R.id.mainFrameLayout, f2, "f2");
        mFragmentTransaction.add(R.id.mainFrameLayout, f3, "f4");
        mFragmentTransaction.add(R.id.mainFrameLayout, f4, "f5");

        mFragmentTransaction.hide(f1);
        mFragmentTransaction.hide(f2);
        mFragmentTransaction.hide(f3);
        mFragmentTransaction.hide(f4);

        mFragmentTransaction.show(f1);
        mFragmentTransaction.commit();
        iv_bar1.setImageResource(R.mipmap.tab1_selected);
        tv_tab01.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
    }

    @Override
    protected void initData() {
//        String [] keyStr={"我是键1","我是键2"};
//        String [] valueStr={"我是值1","我是值2"};
//        AllPublic.addListDES(keyStr,valueStr);
        PackageManager packageManager = context.getPackageManager();
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionname = packInfo.versionName;
            versioncode = packInfo.versionCode;
//            tv_versionname.setText(versionname);
            System.out.println("#$%%$##$%%$##$%^%$#$%#$%$$%=="+versionname+"=="+packInfo.versionCode);

        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ;
        }
        checkUpdata();
//        gaode();

    }
//    private void gaode(){
//        //初始化定位
//        mLocationClient = new AMapLocationClient(getApplicationContext());
//        mLocationListener = new AMapLocationListener() {
//            @Override
//            public void onLocationChanged(AMapLocation aMapLocation) {
//                if (aMapLocation != null) {
//                    if (aMapLocation.getErrorCode() == 0) {
//                        //可在其中解析amapLocation获取相应内容。
//                        aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
////                        aMapLocation.getLatitude();//获取纬度
////                        aMapLocation.getLongitude();//获取经度
////                        aMapLocation.getAccuracy();//获取精度信息
////                        aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
////                        aMapLocation.getCountry();//国家信息
////                        aMapLocation.getProvince();//省信息
//                        aMapLocation.getCity();//城市信息
//                        aMapLocation.getDistrict();//城区信息
////                        aMapLocation.getStreet();//街道信息
////                        aMapLocation.getStreetNum();//街道门牌号信息
////                        aMapLocation.getCityCode();//城市编码
////                        aMapLocation.getAdCode();//地区编码
////                        aMapLocation.getAoiName();//获取当前定位点的AOI信息
////                        aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
////                        aMapLocation.getFloor();//获取当前室内定位的楼层
////                        aMapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
//                        //获取定位时间
////                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
////                        Date date = new Date(aMapLocation.getTime());
////                        df.format(date);
//                        getMyApp().setStr_adress(aMapLocation.getCity());
//                        Log.d("定位：", "城市信息: "+aMapLocation.getCity());
//                        Log.d("定位：", "城区信息: "+aMapLocation.getDistrict());
//                        sendBR();
////                        Log.d("定位：", "获取GPS的当前状态: "+aMapLocation.getGpsAccuracyStatus());
////                        Log.d("定位：", "获取当前室内定位的楼层: "+aMapLocation.getFloor());
//                        toastWk(aMapLocation.getCity());
//                    }else {
//                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
//                        Log.e("AmapError","location Error, ErrCode:"
//                                + aMapLocation.getErrorCode() + ", errInfo:"
//                                + aMapLocation.getErrorInfo());
//                    }
//                }
//            }
//        };
//        //设置定位回调监听
//        mLocationClient.setLocationListener(mLocationListener);
//        //初始化AMapLocationClientOption对象
//        mLocationOption = new AMapLocationClientOption();
//        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        //获取一次定位结果：
//        //该方法默认为false。
//        mLocationOption.setOnceLocation(true);
//        //获取最近3s内精度最高的一次定位结果：
//
//        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//        mLocationOption.setOnceLocationLatest(true);
//        //设置是否返回地址信息（默认返回地址信息）
//        mLocationOption.setNeedAddress(true);
//
//        //给定位客户端对象设置定位参数
//        mLocationClient.setLocationOption(mLocationOption);
//        //启动定位
//        mLocationClient.startLocation();
//
//
//    }
    @Override
    protected void initClick() {
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                if (!mBackKeyPressed) {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    mBackKeyPressed = true;
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            mBackKeyPressed = false;
                        }
                    }, 2000);
                    return true;
                } else {
                    this.finish();
                    System.exit(0);
                }
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 将所有底面的空间，显示为没有点击的图标
     */
    public void disableAllView() {
        iv_bar1.setImageResource(R.mipmap.tab1_normal);
        iv_bar2.setImageResource(R.mipmap.tab2_normal);
        iv_bar3.setImageResource(R.mipmap.tab3_normal);
        iv_bar4.setImageResource(R.mipmap.tab4_normal);
        tv_tab01.setTextColor(getResources().getColor(R.color.color999));
        tv_tab02.setTextColor(getResources().getColor(R.color.color999));
        tv_tab03.setTextColor(getResources().getColor(R.color.color999));
        tv_tab04.setTextColor(getResources().getColor(R.color.color999));
    }
    private void hideF() {
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.hide(f1);
        mFragmentTransaction.hide(f2);
        mFragmentTransaction.hide(f3);
        mFragmentTransaction.hide(f4);
    }
    public void LL1(View view) {
        disableAllView();
        iv_bar1.setImageResource(R.mipmap.tab1_selected);
        tv_tab01.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        hideF();
        mFragmentTransaction.show(f1);
        mFragmentTransaction.commit();
    }
    public void LL2(View view) {
        disableAllView();
        iv_bar2.setImageResource(R.mipmap.tab2_selected);
        tv_tab02.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        hideF();
        mFragmentTransaction.show(f2);
        mFragmentTransaction.commit();
    }
    public void LL3(View view) {
        disableAllView();
        iv_bar3.setImageResource(R.mipmap.tab4_selected);
        tv_tab03.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        hideF();
        mFragmentTransaction.show(f3);
        mFragmentTransaction.commit();
    }
    public void LL4(View view) {
        disableAllView();
        iv_bar4.setImageResource(R.mipmap.tab3_selected);
        tv_tab04.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        hideF();
        mFragmentTransaction.show(f4);
        mFragmentTransaction.commit();
    }
    /**
     * 1.链接服务器
     */
    private void checkUpdata() {
//      showLoad();
        RequestParams params = AllPublic.getParamsVersion(activity, "/getVersion", false);
        Log.d("@", "checkUpdata: "+params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogWk("版本更新：" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("0".equals(jsonObject.getString("code"))) {
                        JSONObject version = jsonObject.getJSONObject("data");
                        String appDownUrl = "";
                        appDownUrl = version.has("versionApk") ? version.getString("versionApk") : "";//下载地址
                        String apkVersionName = version.has("versionNum") ? version.getString("versionNum") : "";//版本号Name
                        int apkVersionCode = version.has("versionCode") ? version.getInt("versionCode") : 0;//版本号Code
                        int mandatoryUpdate = version.has("versionForce") ? version.getInt("versionForce") : 0;//是否强制更新   1强制
                        String updateContent = version.has("versionExplain") ? version.getString("versionExplain") : "";//
//                        //下载地址
//        String appDownUrl = "https://pro-app-tc.fir.im/cab8f4e80d4c0f177302f1c33de55aaf9284e27b.apk?sign=f2eac1a36160c3beb5609ae339096ff2&t=5a698653";
//                        //版本号Name
//        String apkVersionName = "v3.0.0";
////                        //版本号Code
//        int apkVersionCode = 6;
////                        //是否强制更新
//        int mandatoryUpdate = 1;
//                        //更新日志
//        String updateContent = "1.开发中开发中开发中开发中开发中开发中开发中开发中！<br/>" +
//                "2.开发中开发中开发中开发中开发中开发中开发中开发中！<br/>" +
//                "3.开发中开发中开发中开发中开发中开发中开发中开发中！<br/>" +
//                "4.开发中开发中开发中开发中开发中开发中开发中！";
                        getMyApp().setAPKDOWNURL(appDownUrl);
                        getMyApp().setAPPNAMEAZ(apkVersionName + "hhhn.apk");
                        APPNAMEname = apkVersionName + "hhhn.apk";
                        if (apkVersionCode > versioncode) {
                            Log.e("@",apkVersionCode+"");
                            Log.e("@",versioncode+"");
                            LogWk(appDownUrl);
                            showDialog(context, appDownUrl, apkVersionName, mandatoryUpdate, updateContent);
                        } else {
                            Toast.makeText(context, "已经是最新版本", Toast.LENGTH_SHORT).show();
                        }
//                        dismissLoad();
                    } else {
                        Toast.makeText(context, jsonObject.getString("errMsg"), Toast.LENGTH_SHORT).show();
//                        dismissLoad();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
//                    dismissLoad();
                }
//                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
//                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
//                dismissLoad();
            }
            @Override
            public void onFinished() {
//                dismissLoad();
            }
        });
    }

    /**
     * 2弹出新版本提示
     */
    public static void showDialog(final Context context,
                                  final String updataUrl,
                                  final String apkVersionName,
                                  final int mandatoryUpdate,
                                  final String updateContent) {
        final Dialog dialog = new AlertDialog.Builder(context).create();
        final File file = new File(SDCardUtils.getRootDirectory() + UpdataService.DOWNLOADPATH + new UpdataService(APPNAMEname));
        dialog.setCancelable(false);// 可以用“返回键”取消
        dialog.setCanceledOnTouchOutside(false);//
        dialog.show();
        View view = LayoutInflater.from(context).inflate(R.layout.up_version_update_dialog, null);
        dialog.setContentView(view);
        final Button btnOk = (Button) view.findViewById(R.id.btn_update_id_ok);
        Button btnCancel = (Button) view.findViewById(R.id.btn_update_id_cancel);
        TextView tvContent = (TextView) view.findViewById(R.id.tv_update_content);
        TextView tvUpdateTile = (TextView) view.findViewById(R.id.tv_update_title);
        final TextView tvUpdateMsgSize = (TextView) view.findViewById(R.id.tv_update_msg_size);
        tvUpdateTile.setText("最新版本：" + apkVersionName);
        tvContent.setText(Html.fromHtml(updateContent));
        if (mandatoryUpdate == 1) {
            btnCancel.setVisibility(View.GONE);
        }
        if (file.exists() && file.getName().equals(new UpdataService(APPNAMEname))) {
            tvUpdateMsgSize.setText("新版本已经下载，是否安装？");
            btnOk.setText("立即安装");
        } else {
//            tvUpdateMsgSize.setText("新版本大小：自定义版大小");
        }
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();
                if (v.getId() == R.id.btn_update_id_ok) {
                    //安装包存在已经下载---直接安装
                    if (file.exists() && file.getName().equals(new UpdataService(APPNAMEname))) {
                        Intent intent = ApkUtils.getInstallIntent(file);
                        context.startActivity(intent);
                    } else {
                        Toast.makeText(context, "下载中", Toast.LENGTH_SHORT).show();
                        //没有下载，则开启服务下载新版本
                        Intent intent = new Intent(context, UpdataService.class);
                        intent.putExtra("updataUrl", updataUrl);
                        context.startService(intent);
                    }
                }
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

//    public void sendBR(){
//        LogWk("定位成功发送广播");
//        Intent intent = new Intent();
//        intent.setAction(Constants.MBroadcastReceiver);
//        sendBroadcast(intent);
//    }
}
